
import { ApplicationCategory, Application } from '../types';

import { API_BASE_URL, getToken, getUserId, request } from '../../utils';
import { g01DSFind, g01DSFindOne, g01DSRestInsert, g01DSRestUpdate } from './datasource';
import { APPSTORE_APPLICATION_CATEGORY_CLASS_IDENTIFIER, APPSTORE_APPLICATION_CLASS_IDENTIFIER } from '../constants';
import { BitOperator, ComparsionOperator } from '../local';
import { LogicalOperator } from '../local';


export enum ApplicatonPublicStatus {
    INIT = 0,
    PUBLIC = 1,
    AUDITING = 2,
    CANNEL = 3,
    FAIL = 9,
}

export const APPLICATION_PUBLIC_SELECT_OPTIONS = [
    { value: '0', label: '未提交' },
    { value: '1', label: '审核成功' },
    { value: '2', label: '审核中' },
    { value: '3', label: '取消审核' },
    { value: '9', label: '审核失败' },
];

export const APPLICATION_PUBLIC_LABELS = {
    0: '未提交',
    1: '审核成功',
    2: '审核中',
    3: '取消审核',
    9: '审核失败',
};



export const appstoreCategoriesValue2list = (v: string | number): string[] => {
    if (!v || v == '') return [];

    let value = parseInt(v + '');
    let res: string[] = [];
    for (let i = 0; i <= 30; i++) {
        let temp = 1 << i;
        if ((value & temp) === temp) {
            res.push(temp + '');
        }
    }
    console.log(res);
    return res;
}


export const appstoreCategoriesList2value = (v: Array<string>): number => {
    let res = 0;
    for (let i = 0; i < v.length; i++) {
        let value = parseInt(v[i] + '');
        res = res | value;
    }
    return res;
}

export const appstoreGetCategories = async (): Promise<Array<ApplicationCategory>> => {
    let { data, total } = await g01DSFind(APPSTORE_APPLICATION_CATEGORY_CLASS_IDENTIFIER, {});

    return data.filter(item => item.code > 0).map((item, index) => {
        return {
            id: item.id,
            identifier: item.identifier,
            name: item.name,
            code: item.code,
            icon: item.icon,
            description: item.description,
        };
    });
}

export const appstoreGetApplicationByCategory = async (category: number, page: number, pageSize: number, keywords?: string): Promise<{ total: number, data: Array<Application> }> => {
    let { data, total } = await g01DSFind(APPSTORE_APPLICATION_CLASS_IDENTIFIER, {
        expression: {
            operator: { 'bit-operator': BitOperator.And },
            left: 'categories',
            value: category + ''
        },
        page_size: pageSize,
        page: page,
    });
    return {
        total: total,
        data: data.map((item, index) => {
            return obj2application(item);;
        })
    }
}


export const appstoreGetMyApplication = async (page: number, pageSize: number, conditions?: { [key: string]: any }): Promise<{ total: number, data: Array<Application> }> => {
    //
    let userId = getUserId();

    let { data, total } = await g01DSFind(APPSTORE_APPLICATION_CLASS_IDENTIFIER, {
        attributes: [{
            operator: ComparsionOperator.Equal,
            name: 'user_id',
            value: userId
        }],
        page_size: pageSize,
        page: page,
    });
    return {
        total: total,
        data: data.map((item, index) => {
            return obj2application(item);;
        })
    }
}

export const appstoreSaveApplication = async (app: Application): Promise<void> => {
    let values = {
        user_id: app.user_id,
        identifier: app.identifier,
        categories: app.categories,
        version: app.version,
        name: app.name,
        icon: app.icon,
        app_type: app.application_type,
        download: app.download,
        images: app.images,
        options: app.options,
        description: app.description,
    };
    console.log(values);
    let response = await g01DSRestInsert(APPSTORE_APPLICATION_CLASS_IDENTIFIER, values);
    console.log(response);
}


export const appstoreQueryApplicationById = async (identifier: string): Promise<Application | null> => {
    try {
        let item = await g01DSFindOne(APPSTORE_APPLICATION_CLASS_IDENTIFIER, {
            attributes: [
                {
                    name: 'identifier',
                    operator: ComparsionOperator.Equal,
                    value: identifier
                }
            ]
        });

        return item;
    } catch (error) {
        console.error(error);
    }
    return null;
}

export const appstoreAuditApplication = async (identifier: string, status: ApplicatonPublicStatus): Promise<boolean> => {
    try {
        let res = await g01DSRestUpdate(APPSTORE_APPLICATION_CLASS_IDENTIFIER, identifier, {
            status: status
        });
    } catch (error) {
        console.log(error);
    }
    return false;
}

export const appstoreUpdateApplicationStatus = async (identifier: string, publicStatus: number): Promise<void> => {
    //查看token是否设置
    let token = getToken();
    let response = await request({
        url: `${API_BASE_URL}/appstore/app/update_status/${encodeURIComponent(identifier)}/${publicStatus}`,
        method: 'GET',
        headers: {
            'Authorization': token
        },
        dataType: 'application/json',
    });
    return;
}

export const appstoreApplicationCommit = async (identifier: string): Promise<void> => {
    //查看token是否设置
    let token = getToken();
    let response = await request({
        url: `${API_BASE_URL}/appstore/app/commit/${encodeURIComponent(identifier)}`,
        method: 'GET',
        headers: {
            'Authorization': token
        },
        dataType: 'application/json',
    });
    return;
}


export const appstoreApplicationUncommit = async (identifier: string): Promise<void> => {
    //查看token是否设置
    let token = getToken();
    let response = await request({
        url: `${API_BASE_URL}/appstore/app/commit_cannel/${encodeURIComponent(identifier)}`,
        method: 'GET',
        headers: {
            'Authorization': token
        },
        dataType: 'application/json',
    });
    return;
}


export const appstoreRemoveApplicationById = async (identifier: string): Promise<void> => {
    //查看token是否设置
    let token = getToken();
    let response = await request({
        url: `${API_BASE_URL}/appstore/app/remove/${encodeURIComponent(identifier)}`,
        method: 'GET',
        headers: {
            'Authorization': token
        },
        dataType: 'application/json',
    });
    return;
}


const obj2application = (item: any): Application => {
    let images: string[] = [];

    if (item.img_1 && item.img_1 != '') {
        images.push(item.img_1);
    }
    if (item.img_2 && item.img_2 != '') {
        images.push(item.img_2);
    }
    if (item.img_3 && item.img_3 != '') {
        images.push(item.img_3);
    }
    return {
        id: item.id,
        user_id: item.user_id,
        categories: item.categories,
        identifier: item.identifier,
        name: item.name,
        icon: item.icon,
        version: item.version,
        application_type: item.app_type,
        download: item.download,
        public_status: item.is_public,
        images: images,
        suport: item.suport,
        options: item.options,
        description: item.description,
        created_at: item.created_at,
        updated_at: item.updated_at,
    }
}
export default {};